
package com.mall.huohuo.util;

import com.google.common.base.CaseFormat;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

import static com.google.common.collect.Iterables.getFirst;

/**
 *
 * 参数校验，根据参数上的注解
 * @author buhao
 * @version ValidateUtil.java, v 0.1 2018-06-08 14:50 buhao
 */
public class ValidateUtil {
    private static final  Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> ValidateResult validate(T object) {
        ValidateResult validateResult = new ValidateResult();
        validateResult.setResult(true);
        //执行验证
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(object);
        //如果有验证信息，则将第一个取出来包装成异常返回
        ConstraintViolation<T> constraintViolation = getFirst(constraintViolations, null);
        if (constraintViolation != null) {
            validateResult.setResult(false);
            validateResult.setParamName(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, constraintViolation.getPropertyPath().toString()));
            validateResult.setMsg(constraintViolation.getMessage());
        }
        return validateResult;
    }
}


